package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static final Map<String , Method> mapping = new HashMap<>();
    private static File baseDir;
   /* private static File staticDir;*/
    static {
        try {
            baseDir = new File(HandlerMapping.class.getClassLoader().getResource(".").toURI());
/*            staticDir = new File(baseDir,"static");*/
            initMapping();
        } catch (URISyntaxException | ClassNotFoundException e) {
            e.printStackTrace();
        }

   }
    private static void initMapping() throws ClassNotFoundException {
        File dir = new File(baseDir, "com/birdboot/controller");
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File file : subs) {
            String fileName = file.getName();
            String className = fileName.substring(0,fileName.indexOf("."));

            System.out.println("new class "+ className);
            Class cls = Class.forName("com.birdboot.controller." + className);

            if(cls.isAnnotationPresent(Controller.class))
            {
                Method[]methods=cls.getDeclaredMethods();
                for (Method method : methods){
                    if(method.isAnnotationPresent(RequestMapping.class)){
                        RequestMapping reqMapping = method.getAnnotation(RequestMapping.class);
                        String paramValue = reqMapping.value();
                        mapping.put(paramValue,method);
                    }
                }
            }
        }
    }

    public static Method getMethod(String keyPath){
        return mapping.get(keyPath);
    }
}
